package com.xmkj.carwash.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.common.location.LocationUtils;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.utils.LogUtils;
import com.xmkj.carwash.R;
import com.xmkj.carwash.utils.SensorEventHelper;
import com.xmkj.carwash.utils.StatusBarUtil;
import com.xmkj.carwash.utils.ViewToBitmap;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MapLocationActivity extends BaseMvpActivity implements AMap.OnMarkerClickListener, LocationSource, AMap.OnCameraChangeListener, AMapLocationListener {
    public static final String LATITUDU = "LATITUDU";
    public static final String LONGITUDE = "LONGITUDE";
    public static final String REALLADRESS = "REALLADRESS";
    @BindView(R.id.map)
    MapView mapView;
    @BindView(R.id.iv_location)
    ImageView mIvLocation;
    @BindView(R.id.tv_location)
    TextView mTvLocation;
    @BindView(R.id.iv_mine)
    ImageView mIvMine;
    @BindView(R.id.iv_qustion)
    ImageView mIvQustion;
    @BindView(R.id.tv_now)
    TextView mTvNow;
    @BindView(R.id.tv_order)
    TextView mTvOrder;
    @BindView(R.id.iv_one)
    ImageView mIvOne;
    @BindView(R.id.tv_address)
    TextView mTvAddress;
    @BindView(R.id.iv_two)
    ImageView mIvTwo;
    @BindView(R.id.tv_car)
    TextView mTvCar;
    @BindView(R.id.iv_three)
    ImageView mIvThree;
    @BindView(R.id.ll_now)
    LinearLayout mLlNow;
    @BindView(R.id.iv_order_one)
    ImageView mIvOrderOne;
    @BindView(R.id.tv_order_time)
    TextView mTvOrderTime;
    @BindView(R.id.iv_order_two)
    ImageView mIvOrderTwo;
    @BindView(R.id.tv_order_adress)
    TextView mTvOrderAdress;
    @BindView(R.id.iv_order_three)
    ImageView mIvOrderThree;
    @BindView(R.id.tv_order_car)
    TextView mTvOrderCar;
    @BindView(R.id.iv_order_four)
    ImageView mIvOrderFour;
    @BindView(R.id.ll_order)
    LinearLayout mLlOrder;
    @BindView(R.id.ll_main)
    LinearLayout mLlMain;
    @BindView(R.id.tv_wash_money)
    TextView mTvWashMoney;
    @BindView(R.id.tv_call)
    TextView mTvCall;
    @BindView(R.id.iv_message)
    ImageView ivMessage;
    @BindView(R.id.tv_addressss)
    TextView tv_addressss;


    private AMap aMap;
    private SensorEventHelper mSensorHelper;
    private UiSettings uiSettings;
    private boolean mFirstFix = false;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private Marker mLocMarker;
    //中心点的经纬度
    private double centerLatitude = 0;
    private double centerLongitude = 0;
    private String latitudu;
    private String longitude = "";
    private String realladress = "";

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_map_location;
    }

    @Override
    protected void onViewCreated() {
        Bundle saveInstanceState = getSaveInstanceState();
        mapView.onCreate(saveInstanceState);
        latitudu = getIntent().getStringExtra(LATITUDU);
        longitude = getIntent().getStringExtra(LONGITUDE);
        realladress = getIntent().getStringExtra(REALLADRESS);
    }

    @Override
    protected void doLogicFunc() {
//        String[] str = {"nba", "abc", "afc", "afca", "cba", "zz", "qq", "haha","acb","abd"};
//        System.out.println("排序对吗"+Arrays.toString(str));
//        System.out.println("md5"+MD5Utils.MD5Encode("hnihao"));
////        SortUtils.getStringGroup("ad","cc");
//        System.out.println("对吗"+Arrays.toString(SortUtils.getStringGroup("ad","cc")));
//        
//        SortUtils.getFinalString(SortUtils.getStringGroup("aa","ac","df","abc"));
//        System.out.println("你牛逼吧"+SortUtils.getFinalString(SortUtils.getStringGroup("aa","ac","df","abc")));

        getPermission();
        initMap();
        attachClickListener(mIvMine);
        attachClickListener(mIvQustion);
        attachClickListener(ivMessage);
        tv_addressss.setText(realladress);
        pullDataOnNet(latitudu + "", longitude + "");
        LocationUtils.moveCamera(new LatLng(Double.valueOf(latitudu), Double.valueOf(longitude)), aMap);
    }

    @Override
    protected void onViewClicked(View view) {
        super.onViewClicked(view);

    }

    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.setOnMarkerClickListener(this);
            setUpMap();
        }
        mSensorHelper = new SensorEventHelper(this);
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
    }

    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        // 设置默认定位按钮是否显示
        uiSettings = aMap.getUiSettings();
        //显示默认的定位按钮
        uiSettings.setMyLocationButtonEnabled(false);
//        uiSettings.setMyLocationButtonEnabled(false);
//        uiSettings.setZoomPosition(View.GONE);
//        uiSettings.setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);
        uiSettings.setZoomControlsEnabled(false);//隐藏放大 缩小 按钮
        // 可触发定位并显示当前位置
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
        aMap.setOnCameraChangeListener(this);
    }

    private void getPermission() {
        //申请权限
        AndPermission.with(this)
                .requestCode(105)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.READ_PHONE_STATE)
                .rationale(mRationaleListener)
                .send();
    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.setStatusBarColor(this, R.color.black);
    }


    @Override
    protected void setNavigation() {
 /*       super.setNavigation();
        m_statusBar.setVisibility(View.GONE);*/
        setNavigationBack("位置");
    }

    @PermissionYes(105)
    private void openPic() {
        LogUtils.e("成功回调了-->");
        LocationUtils.moveCamera(new LatLng(Double.valueOf(latitudu), Double.valueOf(longitude)), aMap);


    }

    @PermissionNo(105)
    private void injectPic() {
        LogUtils.e("失败回调了-->");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 只需要调用这一句，剩下的 AndPermission 自动完成。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    //申请权限
    private RationaleListener mRationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
            new AlertDialog.Builder(MapLocationActivity.this)
                    .setTitle("友好提醒")
                    .setMessage("没有权限您不能使用定位,拨打电话，请把权限赐给我吧!(如果设置不再提示,您可以在设置中打开权限)")
                    .setPositiveButton("好，给你", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.resume();// 用户同意继续申请。
                        }
                    })
                    .setNegativeButton("我拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.cancel(); // 用户拒绝申请。
                        }
                    }).show();
        }
    };


    

  /*高德地图*******************开始/*/

    @Override
    public void bindKnife() {
        ButterKnife.bind(this);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        String snippet = marker.getSnippet();
        Log.d("snippet", snippet);
//        showToastMsg(snippet.toString());
        return true;
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            if (!mFirstFix) {
                mlocationClient.startLocation();
            }

        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        centerLatitude = cameraPosition.target.latitude;
        centerLongitude = cameraPosition.target.longitude;
        //请求网络 获取数据
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }
        mapView.onPause();
        deactivate();
        mFirstFix = false;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                LatLng location = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                double latitude = amapLocation.getLatitude(); //纬度
                double longitude = amapLocation.getLongitude();//经度
                System.out.println("latitude" + latitude + "longitude" + longitude);
                //提交到网络请求数据


                mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转
                if (!mFirstFix) {
//                    LocationUtils.setMapView(aMap,location);
//                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 18));
                    mFirstFix = true;
                }

            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
                showToastMsg("定位失败");

            }
        }
    }

    //从网上拉去数据
    private void pullDataOnNet(String latitude, String longitude) {


        LatLng latlng1 = new LatLng(Double.valueOf(latitude), Double.valueOf(longitude));
        addMarkersToMap(latlng1);


    }

    //网地图上添加mark
    private void addMarkersToMap(LatLng latlng) {

        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.mipmap.wash_dot);
        Bitmap bitmap = ViewToBitmap.convertViewToBitmap(imageView);
        drawMarkerOnMap(latlng, bitmap);
    }

    //画图
    private Marker drawMarkerOnMap(LatLng point, Bitmap markerIcon) {

        if (aMap != null && point != null) {

            Marker marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 1)
                    .position(point)
//                    .title(id)
                    .icon(BitmapDescriptorFactory.fromBitmap(markerIcon)));
            return marker;

        }

        return null;


    }

      /*高德地图*******************结束/*/
}
